class Solution {
    public String convert(String s, int numRows) {
        // 此时会造成死循环
        if (numRows < 2) return s;
        int d = 2 * numRows - 2;
        int n = s.length();
        StringBuilder ret = new StringBuilder();

        // 找出第一行
        for (int i = 0; i < n; i += d) {
            ret.append(s.charAt(i));
        }
        // 找出中间行
        for (int k = 1;  k < numRows - 1; k++) {
            for (int i = k, j = d - i; i < n || j < n; i += d, j += d) {
                if (i < n) ret.append(s.charAt(i));
                if (j < n) ret.append(s.charAt(j));
            }
        }
        // 找出最后一行
        for (int i = numRows - 1; i < n; i += d) {
            ret.append(s.charAt(i));
        }
        return ret.toString();
    }
}